package com.yugao.fintech.draper.quartz.aspect;

import com.yugao.fintech.draper.quartz.annotation.ScheduledJob;
import com.yugao.fintech.draper.quartz.service.ScheduledJobLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import java.time.Duration;
import java.time.LocalDateTime;

@Slf4j
@Aspect
@RequiredArgsConstructor
public class QuartzJobLogAspect {

    private final ScheduledJobLogService scheduledJobLogService;

    @Around("target(com.yugao.fintech.draper.quartz.task.ScheduledJob)&&args(String)")
    public Object logPointCut(ProceedingJoinPoint pjp) {
        // 开始时间
        LocalDateTime startTime = LocalDateTime.now();
        Class<?> clazz = pjp.getTarget().getClass();
        ScheduledJob quartzJob = clazz.getAnnotation(ScheduledJob.class);
        String beanName = quartzJob.name();
        Object o;
        try {
            // 方法执行
            o = pjp.proceed();
            if (quartzJob.log()) {
                // 结束时间
                LocalDateTime endTime = LocalDateTime.now();
                // 日志信息
                String msg = String.format("执行任务:%s,执行耗时:%d毫秒", beanName, Duration.between(startTime, endTime).toMillis());
                // 保存日志
                scheduledJobLogService.addJobLog(beanName, msg, null);
            }
        } catch (Throwable e) {
            if (quartzJob.log()) {
                scheduledJobLogService.addJobLog(beanName, null, e.getLocalizedMessage());
            }
            throw new RuntimeException(e);
        }
        return o;
    }
}
